#========================================
#    author: Changlong.Zang
#      mail: zclongpop123@163.com
#      time: Sun Nov 22 22:20:18 2020
#========================================
import os
import re
import json
import maya.cmds as mc
import n_env, n_utils
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
def assemble(_seq, _shot):
    '''
    '''
    #- create groups
    for grp in n_env.SHOT_ROOT_GROUPS:
        if not mc.objExists(grp):
            mc.createNode('transform', name=grp)

    #- import animation alembic
    for abc in n_utils.get_ani_cache_list(_seq, _shot):
        _namespace = os.path.basename(os.path.splitext(abc)[0])

        if not mc.namespace(exists=_namespace):
            mc.namespace(add=_namespace)
        mc.namespace(setNamespace=_namespace)
        mc.AbcImport(abc, m='import')
        mc.namespace(setNamespace=':')


    #- import shaders
    shot_info = n_utils.get_shot_info(_seq, _shot)
    assets = shot_info.get('asset', dict())
    for _asset_type, asset_list in assets.iteritems():
        for _asset in asset_list or list():
            shader_file = n_utils.get_asset_shader_file(_asset_type, _asset).replace('\\', '/')
            if shader_file in mc.file(q=True, r=True):
                continue
            _namespace = '{0}_{1}_shader'.format(_asset_type, _asset)
            mc.file(shader_file, r=True, ns=_namespace)

            mapping_file = os.path.join(os.path.dirname(shader_file), n_env.ASSET_MAPPING_FILE_NAME)
            if not os.path.isfile(mapping_file):
                continue

            mapping_data = dict()
            with open(mapping_file, 'r') as f:
                mapping_data = json.load(f)

            #- assign shader
            for sg_name, assign_data in mapping_data[0].iteritems():
                shader_name = assign_data.get('surfaceShader', '')
                shder_node  = '{0}:{1}'.format(_namespace, shader_name)
                if not mc.objExists(shder_node):
                    continue                

                # sg_node = '{0}:{1}'.format(_namespace, sg_name)
                # if not mc.objExists(sg_node):
                    # continue

                geometrys = assign_data.get('meshs_str', list())
                geometrys = [geo.replace('|master', '') for geo in geometrys]
                geometrys = [geo.replace('|', '|{0}:'.format(_asset)) for geo in geometrys]
                geometrys = [re.sub('^\|', '', geo) for geo in geometrys]
                geometrys = [geo for geo in geometrys if mc.objExists(geo)]
                if not geometrys:
                    continue

                mc.select(geometrys)
                mc.hyperShade(assign=shder_node)
                # mc.sets(geometrys, e=True, forceElement=sg_node)

    #- import cfx



if __name__ == '__main__':
    main()
